package com.zxiw.zxedu.cmd;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sdcmnis.sysutils.SDCMApkCode;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Locale;
import java.util.Objects;

/**
 * @author zhangxiaoming
 * @date 2022/8/22
 * @description 执行系统定义广播
 */
public class CmdUtil {
    public static boolean exeCmd(Context context, String packageName, String cmd) {
        return exeCmd(context, packageName, cmd, "", "", "");
    }

    public static boolean exeCmd(Context context, String packageName, String cmd, String val) {
        return exeCmd(context, packageName, cmd, val, "", "");
    }

    public static boolean exeCmd(Context context, String packageName, String cmd, String val, String info, String code) {
        try {
            CmdCls cmdCls = new CmdCls();
            cmdCls.setCmd(cmd);
            cmdCls.setPck(packageName);
            cmdCls.setVal(val);
            cmdCls.setInfo(info);
            cmdCls.setCode(code);
            Gson gson = new Gson();
            String jsonStr = gson.toJson(cmdCls);
            String keyName = String.format(Locale.getDefault(), "/system/etc/publicKey%d.pem", KeyUtil.getKeyFileIndex());
            String publicKey0 = RSACoder.loadKeyF(keyName);
            byte[] enJsonBytes = RSACoder.encrytByPublicKey(jsonStr.getBytes(), publicKey0);
            String baseEnJsonBytes = Base64.encodeToString(enJsonBytes, Base64.DEFAULT);
            Intent intent = new Intent(KeyUtil.ZXIW_ACTION);
            intent.putExtra("msg", baseEnJsonBytes);
            context.sendBroadcast(intent);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean installAPK(Context context, String packageName, String path) throws NullPointerException, FileNotFoundException {
        if (TextUtils.isEmpty(path)) {
            Toast.makeText(context, "安装文件路径为空", Toast.LENGTH_SHORT).show();
            throw new NullPointerException("The installation file path cannot be empty or null");
        }
        File file = new File(path);
        if (!file.exists()) {
            throw new FileNotFoundException("The installation file does not exist");
        }
        String code = SDCMApkCode.getCode(path);
        return CmdUtil.exeCmd(context, packageName, KeyUtil.KEY_APKINSTALL, "", path, code);
    }
}
